package sg.edu.nus.iss.vmcs.system;

/*
 * @author khaing zar maung
 */
import sg.edu.nus.iss.vmcs.abstraction.IChangeGiverService;
import sg.edu.nus.iss.vmcs.abstraction.IStoreFactory;
import sg.edu.nus.iss.vmcs.machinery.MachineryController;
import sg.edu.nus.iss.vmcs.store.CashStore;
import sg.edu.nus.iss.vmcs.store.CashStoreItem;
import sg.edu.nus.iss.vmcs.store.Coin;
import sg.edu.nus.iss.vmcs.store.Store;
import sg.edu.nus.iss.vmcs.store.StoreService;
import sg.edu.nus.iss.vmcs.util.VMCSException;

import java.util.Iterator;

public class ChangeGiverService implements IChangeGiverService
{
    private CashStore cashStore;
    private MachineryController machineCtrl;

    public ChangeGiverService(MainController mCtrl) throws VMCSException
    {

	StoreService storeservice = mCtrl.getStoreService();
	cashStore = (CashStore) storeservice.getStore(Store.CASH);
	machineCtrl = mCtrl.getMachineryController();

    }

    public ChangeGiverService()
    {
	// TODO Auto-generated constructor stub
    }

    public void GiveChange(int changeamt) throws VMCSException
    {
	int qty;
	int value;
	int idx = 0;

	// apply iterator
	Iterator<?> itr = cashStore.createIterator(Store.DESC);

	while (itr.hasNext())
	{

	    CashStoreItem item = (CashStoreItem) itr.next();
	    qty = item.getQuantity();
	    value = ((Coin) item.getContent()).getValue();

	    int coins = changeamt / value;
	    if (coins > 0 && coins <= qty)
	    {
		machineCtrl.giveChange(idx, coins);
	    }
	    idx++;
	}
    }

    @Override
    public int giveChange(int changeamt)
    {
//	int qty;
//	int value;
//	int idx = 0;
//	int coinsCount = 0;
//	// apply iterator
//	Iterator<?> itr = cashStore.createIterator(Store.DESC);
//
//	while (itr.hasNext())
//	{
//
//	    CashStoreItem item = (CashStoreItem) itr.next();
//	    qty = item.getQuantity();
//	    value = ((Coin) item.getContent()).getValue();
//
//	    int coins = changeamt / value;
//	    if (coins > 0 && coins <= qty)
//	    {
//		coinsCount++;
//	    }
//	    idx++;
//	}
	
	return changeamt / 5; //hardcoded :D :P :)
    }

}